/**
 * 
 */
package pl.qsoft.db.storedProc.statement;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.HashMap;
import java.util.Map;

import pl.qsoft.db.annotation.StoredProcedureDefinition;
import pl.qsoft.db.exception.StoredProcedureInvocationException;

/**
 * @author wojciech.kudla@outbox.pl
 *
 */
public class SimpleResultTransformer implements ResultTransformer {

	/* (non-Javadoc)
	 * @see pl.qsoft.db.storedProc.statement.ResultTransformer#transform(java.sql.CallableStatement, pl.qsoft.db.annotation.StoredProcedureDefinition, java.util.Map)
	 */
	public Object transform(CallableStatement stmt, StoredProcedureDefinition procDef, Map<Object, Object> values) throws Exception {
		ResultSet rs = stmt.getResultSet();
		if (rs == null) throw new StoredProcedureInvocationException("The resultset for " + procDef.procedureName() + " is null");
		ResultSetMetaData metaData = rs.getMetaData();
		int colCount = metaData.getColumnCount();
		Map<String, Object> results = new HashMap<String, Object>();
		
		while (rs.next()) {
			for (int i = 1; i < colCount + 1; i++) {
				String columnName = metaData.getColumnName(i);
				Object value = rs.getObject(i);
				results.put(columnName, value);
			}
		}
		return results;
	}

}
